package io.framework.modules.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.framework.common.page.PageData;
import io.framework.common.service.impl.CrudServiceImpl;
import io.framework.common.utils.ConvertUtils;
import io.framework.common.utils.DateUtils;
import io.framework.modules.water.dao.WaterCityRiverDao;
import io.framework.modules.water.dao.WaterDao;
import io.framework.modules.water.dao.WaterFractureSurfaceDao;
import io.framework.modules.water.dao.WaterMonitorDao;
import io.framework.modules.water.dto.WaterDTO;
import io.framework.modules.water.entity.WaterEntity;
import io.framework.modules.water.entity.WaterFractureSurfaceEntity;
import io.framework.modules.water.service.WaterService;
import io.framework.modules.water.vo.WaterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 饮用水源地/检测断面 水质类别表
 *
 * @author Gujq email
 * @since 1.0.0 2020-05-22
 */
@Service
public class WaterServiceImpl extends CrudServiceImpl<WaterDao, WaterEntity, WaterDTO> implements WaterService {

    @Autowired
    private WaterCityRiverDao waterCityRiverDao;

    @Autowired
    private WaterFractureSurfaceDao waterFractureSurfaceDao;

    @Autowired
    private WaterMonitorDao waterMonitorDao;

    @Override
    public QueryWrapper<WaterEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<WaterEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public Map<String, Object> getWaterPassInfo(Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>();
        Integer type = 1;
        if (params.containsKey("type")) {
            type = Integer.parseInt(params.get("type").toString());
        }
        List<Map<String, Object>> passInfo = new ArrayList<>();
        List<Map<String, Object>> passNum = new ArrayList<>();
        //不包含
        Boolean flag = params.containsKey("date");
        if (flag) {
            if (StringUtils.isEmpty(params.get("date").toString())) {
                //空值
                flag = false;
            }
        }
        if (type == 1) {
            //地表水
            passInfo = waterFractureSurfaceDao.getWaterFractureSurfacePassInfo(params);
            passNum = waterFractureSurfaceDao.getWaterFractureSurfacePass(params);
            if (!flag) {
                Map<String, Object> createDateMap = waterFractureSurfaceDao.getCreateDate();
                resultMap.putAll(createDateMap);
            }
        } else if (type == 2) {
            //城镇内河
            passInfo = waterMonitorDao.getWaterMonitorPassInfo(params);
            passNum = waterMonitorDao.getWaterMonitorPass(params);
            if (!flag) {
                Map<String, Object> createDateMap = waterMonitorDao.getCreateDate();
                resultMap.putAll(createDateMap);
            }
        } else if (type == 3) {
            //重点治理城镇内河（湖）
            passInfo = waterCityRiverDao.getWaterCityRiverPassInfo(params);
            passNum = waterCityRiverDao.getWaterCityRiverPass(params);
            if (!flag) {
                Map<String, Object> createDateMap = waterCityRiverDao.getCreateDate();
                resultMap.putAll(createDateMap);
            }
            List<Map<String, Object>> changeInfo = waterCityRiverDao.getWaterCityRiverChangeInfo(params);
            List<Map<String, Object>> changeNum = waterCityRiverDao.getWaterCityRiverChange(params);
            resultMap.put("changeInfo", changeInfo);
            resultMap.put("changeNum", changeNum);
        } else if (type == 4) {
            //饮用水源
            passInfo = new ArrayList<>();
            passNum = new ArrayList<>();
            resultMap.put("createDate", null);
        }
        resultMap.put("passInfo", passInfo);
        resultMap.put("passNum", passNum);
        return resultMap;

    }

    @Override
    public Map<String, Object> getwaterRateInfo(Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>(3);
        Integer type = 1;
        if (params.containsKey("type")) {
            type = Integer.parseInt(params.get("type").toString());
        }
        if (type == 1) {
            //地表水
            params.put("waterType",2 );
            if(params.get("date")!=null){
                String date = params.get("date").toString();

                params.put("year",date.split("-")[0]);

                String month = date.split("-")[1];
                if(month.substring(0,1).equals("0")){
                    month = month.replace("0","");
                }

                params.put("month",month);
                resultMap.put("createDate", params.get("date").toString());
                resultMap.put("waterRateInfo", baseDao.getWaterRateInfo(params));
                resultMap.put("waterRateNum", baseDao.getWaterRate(params));

            }else {
                return setResultMap1and4(2, params);
            }

//            return setResultMap1and4(2, params);
        } else if (type == 2) {
            //城镇内河
            if (!params.containsKey("date") || StringUtils.isBlank(params.get("date").toString())) {
                resultMap.putAll(waterMonitorDao.getCreateDate());
                params.put("date", resultMap.get("createDate"));
            }
            resultMap.put("waterRateInfo", waterMonitorDao.getWaterRateInfo(params));
            resultMap.put("waterRateNum", waterMonitorDao.getWaterRate(params));
        } else if (type == 3) {
            //重点治理城镇内河（湖）
            if (!params.containsKey("date") || StringUtils.isBlank(params.get("date").toString())) {
                resultMap.putAll(waterCityRiverDao.getCreateDate());
                params.put("date", resultMap.get("createDate"));
            }
            resultMap.put("waterRateInfo", waterCityRiverDao.getWaterRateInfo(params));
            resultMap.put("waterRateNum", waterCityRiverDao.getWaterRate(params));
        } else if (type == 4) {
            //饮用水源
             params.put("waterType", 1);
             if(params.get("date")!=null){
                 String date = params.get("date").toString();

                 params.put("year",date.split("-")[0]);

                 String month = date.split("-")[1];
                 if(month.substring(0,1).equals("0")){
                     month = month.replace("0","");
                 }

                 params.put("month",month);
                 resultMap.put("createDate", params.get("date").toString());
                 resultMap.put("waterRateInfo", baseDao.getWaterRateInfo(params));
                 resultMap.put("waterRateNum", baseDao.getWaterRate(params));

             }else {
                 return setResultMap1and4(1, params);
             }




        }
        return resultMap;
    }

    private Map<String, Object> setResultMap1and4(Integer waterType, Map<String, Object> params) {
        Map<String, Object> resultMap = new HashMap<>(3);
        if (!params.containsKey("year") || !params.containsKey("month")) {
            //查询最新年月
            params.putAll(baseDao.getCreateDate(waterType));
        }



        String month = params.get("month").toString();
        if (month.length() == 1) month = "0" + month;
        resultMap.put("createDate", params.get("year").toString() + "-" + month);
        params.put("waterType", waterType);
        resultMap.put("waterRateInfo", baseDao.getWaterRateInfo(params));
        resultMap.put("waterRateNum", baseDao.getWaterRate(params));
        return resultMap;
    }

    @Override
    public WaterDTO getWaterInfoByStationId(Map<String, Object> params) {
        Integer type = Integer.parseInt(params.get("type").toString());
        if (type == 1) {
            params.put("type", 2);
        } else {
            params.put("type", 1);
        }
        WaterEntity entity = baseDao.getWaterInfoByStationId(params);

        return ConvertUtils.sourceToTarget(entity, WaterDTO.class);
    }

    @Override
    public Boolean checkData(Integer type, String month) {
        month = DateUtils.format(DateUtils.parse(month, DateUtils.DATE_MONTH_PATTERN), DateUtils.DATE_YEAR_PATTERN);
        Integer count = baseDao.checkData(type == 4 ? 1 : 2, month);
        return count > 0 ? true : false;
    }

    @Override
    public void deleteInfoByDate(Integer type, String year) {

        baseDao.deleteInfoByDate(type, year);
    }

    @Override
    public PageData<WaterVo> pageList(Map<String, Object> params) {
        List<WaterVo> list = new ArrayList<>();
        //查询count
        Integer count = baseDao.countGroupByStationId(params);
        if (count > 0) {
            //组装参数
            Integer page = Integer.valueOf((String) params.get("page"));
            Integer limit = Integer.valueOf((String) params.get("limit"));
            params.put("start", (page - 1) * limit);
            params.put("limit", limit);
            //根据 stationId 分组 分页查询
            List<Long> stationIds = baseDao.getStationIds(params);
            if (!stationIds.isEmpty() && stationIds.size() > 0) {
                //查询 stationId 对应数据
                params.put("stationIds", stationIds);
                List<WaterEntity> waterEntities = baseDao.listByMapAndStationIds(params);
                stationIds.stream().forEach(stationId -> {
                    WaterVo waterVo = new WaterVo();
                    //筛选 stationId 对应数据
                    List<WaterEntity> wdl = waterEntities.stream().filter(waterEntity -> waterEntity.getStationId().equals(stationId)).collect(Collectors.toList());
                    if (!wdl.isEmpty() && wdl.size() > 0) {
                        //设置公共属性值
                        WaterEntity we = wdl.get(0);
                        waterVo.setName(we.getName());
                        waterVo.setStationId(we.getStationId());
                        waterVo.setType(we.getType());
                        waterVo.setYearAvg(we.getYearAvg());
                        waterVo.setPassRate(we.getPassRate());
                        if (StringUtils.isNotBlank(we.getDrRemarks())) waterVo.setDrRemarks(we.getDrRemarks());
                        //设置月份属性值
                        Class<?> waterVoClass = waterVo.getClass();
                        wdl.stream().forEach(waterEntity -> {
                            try {
                                Field field = waterVoClass.getDeclaredField("month" + waterEntity.getMonthNow() + "Classify");
                                field.setAccessible(true);
                                field.set(waterVo, waterEntity.getMonthClassify());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                    list.add(waterVo);
                });
                //地表
                if (params.containsKey("type")) {
                    Integer type = Integer.valueOf((String) params.get("type"));
                    if (type == 2) {
                        //查询 stationId 对应 地表水 监测断面水质评价表 数据
                        List<WaterFractureSurfaceEntity> waterFractureSurfaceEntityList = waterFractureSurfaceDao.listByMapAndStationIds(params);
                        if(waterFractureSurfaceEntityList.size()>0){
                            list.stream().forEach(waterVo -> {
                                WaterFractureSurfaceEntity waterFractureSurfaceEntity = waterFractureSurfaceEntityList.stream()
                                        .filter(w -> w.getStationId().equals(waterVo.getStationId())).findFirst().get();
                                waterVo.setWaterFractureSurfaceEntity(waterFractureSurfaceEntity);
                            });
                        }

                    }
                }
            }
        }
        return new PageData<>(list, count);
    }

    @Override
    public Map<String, Object> maxTime() {
        Map<String, Object> timeMap = waterFractureSurfaceDao.maxTime();
        return timeMap;
    }


}
